package com.xdream.distribution.service.impl;

import com.alibaba.fastjson.JSON;
import com.xdream.distribution.entity.LevelGrade;
import com.xdream.distribution.entity.UserProfit;
import com.xdream.distribution.enums.ProfitType;
import com.xdream.distribution.enums.State;
import com.xdream.distribution.enums.SystemParam;
import com.xdream.distribution.service.ICalculFeeService;
import com.xdream.distribution.service.ILevelGradeService;
import com.xdream.distribution.service.IUserProfitService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("calculFeeService")
public class CalculFeeService implements ICalculFeeService {

    @Resource(name = "levelGradeService")
    private ILevelGradeService levelGradeService;

    @Resource(name="userProfitService")
    private IUserProfitService userProfitService;
    /**
     * 计算用户手续费
     * @param fee  总手续费
     * @param userId  用户id
     * @return
     * @throws Exception
     */
    public String calculProfit(BigDecimal fee,Long userId) throws Exception {

        //本级用户分润
        BigDecimal profit = BigDecimal.ZERO;
        //上级用户分润
        BigDecimal sProfit=BigDecimal.ZERO;
        //百分比计算
        if(SystemParam.SHAREPROFITTYPE.paramName.equals(ProfitType.PERCENT.type)){
            List<LevelGrade> levelGradeList=levelGradeService.findAllLevel(State.NORMAL.stateCode);
            profit = fee.multiply(levelGradeList.get(0).getLevelRate()).setScale(2, RoundingMode.DOWN);
            sProfit = fee.multiply(levelGradeList.get(1).getLevelRate()).setScale(2, RoundingMode.DOWN);
        }else{
            //直属用户手续费
            BigDecimal dirtUserFee=fee.multiply(new BigDecimal(SystemParam.UserRate.paramName).divide(new BigDecimal("100"))).setScale(2, RoundingMode.DOWN);
            //剩下参与分润的钱
            BigDecimal surplusFee=fee.subtract(dirtUserFee);
            UserProfit  userProfit=userProfitService.findByUserId(userId, State.NORMAL.stateCode);
            UserProfit  suidProfit=userProfitService.findByUserId(userProfit.getUsid(), State.NORMAL.stateCode);
            BigDecimal diffRate=userProfit.getFee().subtract(suidProfit.getFee());
            sProfit=surplusFee.multiply(diffRate.divide(new BigDecimal("100"))).setScale(2, RoundingMode.DOWN);
        }
        Map<String,Object> hashMap = new HashMap<String, Object>();
        hashMap.put("code","success");
        hashMap.put("message","操作成功");
        hashMap.put("profit",profit);
        hashMap.put("sProfit",sProfit);
        String resultJson= JSON.toJSONString(hashMap);
        return resultJson;
    }
}
